package com.qf.sl.youshare.utils;

import java.io.*;

/**
 * Created by IDEA
 * User : sl
 * on 2015/2/6.
 * 18:46
 */
public final class StreamUtils {

    //工具类不能够继承,不能够实例化
    private StreamUtils(){

    }

    public static void close(Object stream){
        if (stream != null) {
            try {
                if (stream instanceof InputStream){
                    ((InputStream) stream).close();
                }else if (stream instanceof OutputStream){
                    ((OutputStream) stream).close();
                }else if (stream instanceof Reader){
                    ((Reader) stream).close();
                }else if (stream instanceof Writer){
                    ((Writer) stream).close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 持续读取 in 中的数据
     * @param inputStream
     * @param outputStream
     * @return
     */
    public static long readStram(InputStream inputStream, OutputStream outputStream) throws IOException {
        long ret = 0;
        if (inputStream != null && outputStream != null) {
            byte[] buf = new byte[128];
            int len = 0;
            while (true){
                len = inputStream.read(buf);

                if (len == -1){
                    break;
                }
                ret += len;
                outputStream.write(buf, 0, len);
            }
            buf = null;
        }
        return ret;
    }

    /**
     * 将输入流读取到字节数组中
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static byte[] readStream(InputStream inputStream) throws IOException {
        byte[] ret = null;

        if (inputStream != null) {
            //这个buf 必须显示释放, 也就是 buf = null;
            byte[] buf = new byte[128];

            int len;

            ByteArrayOutputStream bout = null;

            bout = new ByteArrayOutputStream();

            readStram(inputStream,bout);

//            while (true){
//                len = inputStream.read(buf);
//                if (len == -1){
//                    break;
//                }
//                bout.write(buf, 0, len);
//            }
            //bout.toByteArray() 再返回的时候, 会将内部的数组
            //  复制一份,然后返回给 ret
            ret = bout.toByteArray();

            close(bout);
            bout = null;
            buf = null;
        }

        return ret;
    }

}
